package com.tieto.springboot.demo.customsession;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

import com.google.common.cache.Cache;

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
	
	private String 				mSessionId = null;
	private HttpServletRequest  mReqeust 	= null;
	private CustomSession       mSession  	= null;

	public CustomHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	
	public CustomHttpServletRequestWrapper(String pSessionId, HttpServletRequest pRequest){
		super(pRequest);
		this.mSessionId =  pSessionId;
		this.mReqeust = pRequest;
	}
	
	@Override
	public HttpSession getSession(boolean create) {
		Cache<String, CustomSession> sessionCache = LocalCache.getSessionCache();
		mSession = sessionCache.getIfPresent(mSessionId);
		if (mSession == null && create) {
			mSession = new CustomSession(mSessionId,mReqeust.getServletContext());
			sessionCache.put(mSessionId, mSession);
		}

		return mSession;
	}
	
	@Override
	public HttpSession getSession() {
		return getSession(true);
	}

	@Override
	public ServletRequest getRequest() {
		return mReqeust;
	}
}
